<!--裁剪
https://github.com/fengyuanchen/cropper
http://blog.csdn.net/u012552049/article/details/72829473
http://www.html5tricks.com/jquery-image-cut.html
https://www.cnblogs.com/Travel/p/4624929.html-->

<!--参考
https://www.52doutu.cn
http://www.bbsnet.com
http://www.doutula.com
http://www.adoutu.com
-->

<!--html2canvas文档
http://caibaojian.com/html2canvas.html-->

<!--解决Canvas.toDataURL 图片跨域的问题
http://www.jb51.net/article/83916.htm

截图区域有任何一张跨域图片（包括css背景图片），都会报错。
-->

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Title</title>
    <link rel="stylesheet" href="bootstrap.min.css">
    <link rel="stylesheet" href="//apps.bdimg.com/libs/jqueryui/1.10.4/css/jquery-ui.min.css">
    <style>

        #imgbox,#console{
            /*border: 1px solid #999;*/
            /*border-radius: 3px;*/
        }
        #previewImg{
            width: 100%;
            max-width: 100%;
            height: auto;
        }
        #output{
            padding: 0;
            margin: 0;
            position: relative;
            line-height: 53px;
            font-size: 53px;
            /*border:1px solid indianred;*/
            overflow: hidden;
        }
        #imgbox{
            position: relative;
            padding: 0;
            margin: 0;
            border: 0;
            /*width: 500px;
            height: 300px;*/
            padding: 5px;
            border:1px solid #d3d3d3;
        }
        .drag_element{
            position: absolute;
            border: 1px dashed #ff0;
            padding: 10px;
            /*margin: 10px;*/
            cursor: move;
            line-height: 53px;
            font-size: 53px;
        }
        .drag_element_blured{
            border: 1px dashed transparent;
        }
        .appendText{
            text-align: left;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            color: #000;
            margin: 0;
            outline: none;
            font-family: Microsoft YaHei,"微软雅黑";
        }
        #console{
            padding: 20px;
        }
        .fanzhuan{
            -webkit-transform: rotateY(180deg);
            -moz-transform: rotateY(180deg);
            -ms-transform: rotateY(180deg);
            -o-transform: rotateY(180deg);
            transform: rotateY(180deg);
        }
        .desaturate{
            filter: grayscale(100%);
            -webkit-filter: grayscale(100%);
            -moz-filter: grayscale(100%);
            -ms-filter: grayscale(100%);
            -o-filter: grayscale(100%);
        }
        .ui-resizable-s{
            /*height: 0;*/
        }
        .ui-resizable-se{
            right: 3px;
            bottom: 3px;
        }
        .ui-icon, .ui-widget-content .ui-icon{
            background-image: url(img/ui-icons_222222_256x240.png);
            /*background: none;
            border-top:10px solid transparent;
            border-bottom:0 solid transparent;
            border-right:10px solid #333;
            width:0;
            height:0;
            line-height: 0;
            font-size: 0;*/
        }
        ul,li{list-style-type: none}
        .color1{
            background-color: #337ab7;
            width: 50px;
            height: 20px;
            display: block;
        }
        .color-selected{
            box-shadow: 0 0 10px #000
        }
        .group-buttons{

        }
        .group-buttons-colors{
            display: table;
            border:1px solid #d3d3d3;
            padding: 0 3px;
        }
        .group-buttons-colors>ul{
            display: table-row;
        }
        .group-buttons-colors>ul>li{
            display:table-cell;
            padding: 5px 3px;
            cursor: pointer;
        }

        .currentSelected{
            /*border:1px dashed #ff0;*/
        }
    </style>
</head>
<body>

<div class="container">
    <div class="row">
        <div id="imgbox" class="col-md-6 ui-widget-content">
            <div id="output">
                <img src="" id="previewImg" crossorigin="anonymous" alt="">
            </div>
        </div>
        <div id="console" class="col-md-6">
            <!--颜色-->
            <div class="group-buttons group-buttons-colors" id="group-buttons-colors"></div>
            <!--字体-->
            <div class="group-buttons group-buttons-fontSize" id="group-buttons-fontSize">
                <select name="fontSize" id="fontSize">
                    <option value="12">12</option>
                    <option value="14">14</option>
                    <option value="16">16</option>
                    <option value="18">18</option>
                    <option value="20">20</option>
                    <option value="24">24</option>
                    <option value="30">30</option>
                    <option value="36" selected>36</option>
                    <option value="48">48</option>
                    <option value="60">60</option>
                    <option value="72">72</option>
                </select>
                <select name="fontFamily" id="fontFamily">
                    <option value="1">宋体</option>
                    <option value="2">黑体</option>
                    <option value="3">微软雅黑</option>
                </select>
                <span>B</span>

            </div>
            <!--加粗，下划线，斜体，字体，字间距，行间距-->
            <button id="btn-getImg">getImg</button>
            <button id="btn-download">download</button>
            <button id="btn-reset">reset</button>
            <!--<button id="btn-pen">画笔</button>
            <button>清空画布</button>
            <button>上传本地图片</button>-->
            <br/>
            <!--<button id="btn-fanzhuan">水平翻转</button>
            <button id="btn-black">黑白照</button>-->
        </div>
    </div>
</div>

<!--<canvas id="canvas" style="width: 200px;height: 200px;"></canvas>-->

<script src="//apps.bdimg.com/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//apps.bdimg.com/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script src="https://cdn.bootcss.com/html2canvas/0.5.0-beta4/html2canvas.min.js"></script>
<script type="text/javascript">

    var source_src='2.png';

    $('#previewImg').attr('src',source_src);

    $('#previewImg').load(function(){
        var _maxW= $('#previewImg').width(),
        _maxH= $('#previewImg').height(),
        _art=_maxW/_maxH;

        $( "#output" ).resizable({
            //animate: true,
            //helper: "ui-resizable-helper",
            maxWidth: _maxW,
            maxHeight: _maxH,
            minWidth: 200,
            minHeight: 150,
            aspectRatio: _art  //保持纵横比
        });
    });


    //$('#output').draggable({ containment: "parent" });
    //鼠标按下画布拖动
    /*$('#output').mousedown(function(){
        $(this).css('cursor','move');
    }).mouseup(function(){
        $(this).css('cursor','initial');
    });*/


    $('#imgbox').dblclick(function(e){

        var div1 =document.createElement('div');
        div1.className='drag_element';

        div1.innerHTML='<p class="appendText" style="font-size: '+Font.getCurrFontSize()+';min-width: 30px;user-select: text;color: '+Colors.getCurrColor()+';" contenteditable="true"></p>';

        $('#output').append(div1);

        //获得焦点
        $(this).find('.appendText:last').focus();

        //设置相对坐标
        var offset = $(this).offset();
        var relativeX = (e.pageX - offset.left)-20;
        var relativeY = (e.pageY - offset.top)-20;
        $(this).find('.drag_element:last').css({'left':relativeX,'top':relativeY});

        //拖拽
        $('.drag_element').draggable({ containment: "parent" });
    });

    //当前文本框获得焦点
    $('#imgbox').on('click','.appendText',function(){
        $(this).focus();
        $(this).parent('.drag_element').removeClass('drag_element_blured').addClass('currentSelected').siblings().removeClass('currentSelected');//当前选中
    });
    //失去焦点，文本框为空时移除
    $('#imgbox').on('blur','.appendText',function(){
        if($(this).text()=='')
            $(this).parent('.drag_element').remove();
        else {
            $(this).parent('.drag_element').addClass('drag_element_blured');
        }
    });
    //双击文本框时取消冒泡，防止误操作。
    $('#imgbox').on('dblclick','.appendText',function(e){
        e.stopPropagation();
        return false;
    });

    //生成图片
    $('#btn-getImg').click(function(){

        /*var mycanvas = document.getElementById("canvas");
        var image = mycanvas.toDataURL("image/jpg");
        var w=window.open('about:blank','image from canvas');
        w.document.write("<img src='"+image+"' alt='from canvas'/>");*/

        html2_canvas();
    });
    //下载此图片
    $('#btn-download').click(function(){
        download();
    });

    function download(){
        html2_canvas(1);
    }

    //解决模糊问题：https://github.com/niklasvh/html2canvas/pull/1087

    function html2_canvas(isDownload){
        $('.ui-resizable-handle.ui-icon').hide();

        html2canvas(document.getElementById("output"), {
            dpi: 144,
            allowTaint: true,
            taintTest: false,
            onrendered: function(canvas) {

                canvas.id = "mycanvas";
                //生成base64图片数据
                var dataUrl = canvas.toDataURL();
                /*var newImg = document.createElement("img");
                 newImg.src =  dataUrl;
                 document.body.appendChild(newImg);*/

                $('.drag_element').remove();//移除文字区
                $('#previewImg').attr('src',dataUrl).removeClass();//加载新图片
                $('.ui-resizable-handle.ui-icon').show();

                //下载此图片
                if(isDownload){
                    var triggerDownload = $("<a>").attr("href", $('#previewImg').attr('src')).attr("download", '下载.png').appendTo("body");
                    triggerDownload[0].click();
                    triggerDownload.remove();
                }
            }
        });
    }

    //重置
    $('#btn-reset').click(function(){
        $('.drag_element').remove();
        $('#previewImg').attr('src',source_src);
    });
    //翻转
    $('#btn-fanzhuan').click(function(){
        $('#previewImg').toggleClass('fanzhuan')
    })
    //黑白
    $('#btn-black').click(function(){
        $('#previewImg').toggleClass('desaturate')
    })


    /*
    * 颜色
    * */
    var Colors={
        Init:function(){
            Colors.generateColors();
        },
        //生成颜色选区
        generateColors:function(){
            var _html='<li class="color-selected"><span class="color1" style="background-color: #000"></span></li>';
            for(var i=0;i<8;i++){
                _html+='<li><span class="color1" style="background-color: '+Colors.getRandomColor2()+'"></span></li>';
            }
            $('.group-buttons-colors').append('<ul>'+_html+'</ul>');

            $('body').on('click','.group-buttons-colors>ul>li',function(){
                $(this).addClass('color-selected').siblings().removeClass('color-selected');
                $('.currentSelected>.appendText').css('color',Colors.getCurrColor());
            })
        },
        //获得当前颜色值
        getCurrColor:function(){
            return $('.color-selected>span').css('background-color');
        },
        RandomNumBoth:function(Min, Max) {
            var Range = Max - Min;
            var Rand = Math.random();
            var num = Min + Math.round(Rand * Range);
            return num;
        },
        getRandomColor2:function() {
            var colorList = ["#ba3232", "#333", "#4866d6", "#bc2fad", "#999", "#2fbc5e", "#b2cd45", "#e9a854", "#e96d54", "#f6190e", "#D9534F"];
            return colorList[Colors.RandomNumBoth(1, colorList.length) - 1];
        }
    };

    /*
    * 字体
    * */
    var Font={
        Init:function(){


        } ,
        getCurrFontSize:function(){
            return $('#fontSize').val()+'px';
        }

    }

    /*
    * 画笔
    * */
    var Pen={
      Init:function(){

        $('#btn-pen').click(function(){

        })

      }


    };



    var Page={
        Init:function(){
            Colors.Init();
            Pen.Init();
        }

    };
    Page.Init();
</script>
</body>
</html>